<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>【测试】AI量化交易系统</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
    <style>
        .stock-card {
            transition: all 0.3s ease;
            margin-bottom: 1rem;
        }
        .stock-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        .advice-buy { border-left: 4px solid #28a745; }
        .advice-sell { border-left: 4px solid #dc3545; }
        .advice-hold { border-left: 4px solid #ffc107; }
        .advice-exit { border-left: 4px solid #6c757d; }
        .positive { color: #dc3545; }
        .negative { color: #28a745; }
        .neutral { color: #6c757d; }
        .analysis-panel {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
        }
        #klineChart {
            height: 500px;
            width: 100%;
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            display: none;
        }
        .loading-spinner {
            background: white;
            padding: 30px;
            border-radius: 10px;
            text-align: center;
        }
    </style>
</head>
<body>
<!-- 加载遮罩层 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner">
        <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <div class="mt-3">
            <h5>AI分析中，请稍候...</h5>
            <p class="text-muted" id="loadingText">正在获取股票数据并进行深度分析</p>
            <div class="progress mt-2" style="height: 6px;">
                <div class="progress-bar progress-bar-striped progress-bar-animated"
                     id="progressBar" style="width: 0%"></div>
            </div>
            <small class="text-muted" id="timeRemaining">预计需要1分钟，请耐心等待</small>
        </div>
    </div>
</div>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container">
        <a class="navbar-brand" href="/quant/">
            <i class="fas fa-robot"></i> AI量化交易系统
        </a>
    </div>
</nav>

<div class="container mt-4">
    <!-- 搜索区域 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title"><i class="fas fa-search"></i> 股票分析</h5>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="input-group">
                                <input type="text" class="form-control" id="stockCodeInput"
                                       placeholder="输入股票代码，如：000001、600036" value="000001">
                                <button class="btn btn-primary" onclick="analyzeStock()" id="analyzeBtn">
                                    <i class="fas fa-chart-line"></i> 开始分析
                                </button>
                            </div>
                            <div class="form-text">支持沪深A股股票代码</div>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" id="daysSelect">
                                <option value="30" selected>最近30天</option>
                                <option value="90">最近90天</option>
                                <option value="180">最近180天</option>
                                <option value="365">最近1年</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 分析结果 -->
    <div class="row" id="analysisResult" style="display: none;">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 id="stockTitle">分析结果</h5>
                </div>
                <div class="card-body">
                    <!-- K线图 -->
<!--                    <div class="row mb-4">-->
<!--                        <div class="col-12">-->
<!--                            <h6><i class="fas fa-chart-bar"></i> K线图 (日线)</h6>-->
<!--                            <div id="klineChart"></div>-->
<!--                        </div>-->
<!--                    </div>-->

                    <!-- 交易建议 -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="card" id="adviceCard">
                                <div class="card-body">
                                    <h6><i class="fas fa-lightbulb"></i> AI交易建议</h6>
                                    <div id="adviceContent">
                                        <!-- 建议内容动态加载 -->
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <h6><i class="fas fa-info-circle"></i> 股票信息</h6>
                                    <div id="stockInfo">
                                        <!-- 股票信息动态加载 -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 使用说明 -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <h5><i class="fas fa-book"></i> 使用说明</h5>
                    <ul>
                        <li>输入股票代码获取近180天历史数据和技术分析</li>
                        <li>系统基于DeepSeek大模型生成交易建议</li>
                        <li>建议类型包括：加仓、减仓、持有、空仓</li>
                        <li>分析结果包含目标价格和止损价格建议</li>
                        <li><strong>注意：AI分析可能需要1分钟时间，请耐心等待</strong></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    let klineChart;
    let analysisTimeout;
    let progressInterval;
    let startTime;

    // 初始化ECharts
    function initChart() {
        const chartDom = document.getElementById('klineChart');

        // 确保容器有正确的尺寸
        chartDom.style.width = '100%';
        chartDom.style.height = '500px';

        klineChart = echarts.init(chartDom);

        // 更积极的resize处理
        const resizeChart = () => {
            klineChart.resize({
                width: chartDom.clientWidth,
                height: chartDom.clientHeight
            });
        };

        window.addEventListener('resize', resizeChart);

        // 初始调整一次
        setTimeout(resizeChart, 50);
    }

    // 显示加载动画
    function showLoading() {
        const overlay = document.getElementById('loadingOverlay');
        const analyzeBtn = document.getElementById('analyzeBtn');

        overlay.style.display = 'flex';
        analyzeBtn.disabled = true;
        analyzeBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 分析中...';

        // 重置进度条
        const progressBar = document.getElementById('progressBar');
        progressBar.style.width = '0%';

        // 开始时间
        startTime = Date.now();

        // 更新进度条
        progressInterval = setInterval(updateProgress, 500);

        // 设置1分钟超时
        analysisTimeout = setTimeout(function() {
            hideLoading();
            alert('分析超时，请稍后重试或检查网络连接');
        }, 60000); // 1分钟超时
    }

    // 隐藏加载动画
    function hideLoading() {
        const overlay = document.getElementById('loadingOverlay');
        const analyzeBtn = document.getElementById('analyzeBtn');

        overlay.style.display = 'none';
        analyzeBtn.disabled = false;
        analyzeBtn.innerHTML = '<i class="fas fa-chart-line"></i> 开始分析';

        // 清除定时器
        if (analysisTimeout) {
            clearTimeout(analysisTimeout);
        }
        if (progressInterval) {
            clearInterval(progressInterval);
        }
    }

    // 更新进度条
    function updateProgress() {
        const elapsed = Date.now() - startTime;
        const progress = Math.min((elapsed / 60000) * 100, 95); // 最多到95%，留5%给最后完成
        const progressBar = document.getElementById('progressBar');
        const timeRemaining = document.getElementById('timeRemaining');

        progressBar.style.width = progress + '%';

        // 更新剩余时间
        const remainingSeconds = Math.max(0, Math.ceil((60000 - elapsed) / 1000));
        timeRemaining.textContent = `预计剩余 ${remainingSeconds} 秒`;

        // 更新加载文本
        const loadingText = document.getElementById('loadingText');
        if (progress < 30) {
            loadingText.textContent = '正在获取股票历史数据...';
        } else if (progress < 60) {
            loadingText.textContent = '正在计算技术指标...';
        } else if (progress < 85) {
            loadingText.textContent = 'AI模型分析中...';
        } else {
            loadingText.textContent = '生成最终分析报告...';
        }
    }

    // 完成进度条
    function completeProgress() {
        const progressBar = document.getElementById('progressBar');
        progressBar.style.width = '100%';
        progressBar.classList.remove('progress-bar-animated');
    }

    // 分析股票
    async function analyzeStock() {
        const stockCode = document.getElementById('stockCodeInput').value.trim();
        const days = document.getElementById('daysSelect').value;

        if (!stockCode) {
            alert('请输入股票代码');
            return;
        }

        // 显示加载动画
        showLoading();

        try {
            // 创建AbortController用于超时控制
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 55000); // 55秒超时，给前端留5秒处理时间

            const response = await fetch('/quant/api/trading/analyze', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    stockCode: stockCode,
                    days: parseInt(days)
                }),
                signal: controller.signal
            });

            clearTimeout(timeoutId);

            const result = await response.json();

            // 完成进度条
            completeProgress();

            // 短暂延迟后隐藏加载动画，让用户看到完成状态
            setTimeout(() => {
                hideLoading();

                if (result.code === 0) {
                    displayAnalysisResult(result.data);
                } else {
                    throw new Error(result.msg);
                }
            }, 500);

        } catch (error) {
            hideLoading();

            if (error.name === 'AbortError') {
                alert('请求超时（1分钟），请稍后重试或检查网络连接');
            } else {
                alert('分析失败: ' + error.message);
            }
        }
    }

    // 显示分析结果
    function displayAnalysisResult(data) {
        document.getElementById('analysisResult').style.display = 'block';
        document.getElementById('stockTitle').textContent =
            `${data.stockCode} ${data.stockName} - AI量化分析`;

        // 显示股票信息
        displayStockInfo(data);

        // 显示K线图
        // displayKLineChart(data.historyData);

        // 显示交易建议
        displayTradingAdvice(data.advice);

        // 滚动到分析结果区域
        document.getElementById('analysisResult').scrollIntoView({
            behavior: 'smooth'
        });
    }

    // 显示股票信息
    function displayStockInfo(data) {
        const stockInfoDiv = document.getElementById('stockInfo');

        // 安全地处理可能为null的值
        const currentPrice = data.currentPrice || 0;
        const changeRate = data.changeRate || 0;

        // 计算涨跌幅颜色和图标
        let changeClass, changeIcon;
        if (changeRate > 0) {
            changeClass = 'positive';
            changeIcon = '▲';
        } else if (changeRate < 0) {
            changeClass = 'negative';
            changeIcon = '▼';
        } else {
            changeClass = 'neutral';
            changeIcon = '●';
        }

        // 安全地格式化数字
        const formatNumber = (num) => {
            if (num === null || num === undefined) return '--';
            return typeof num === 'number' ? num.toFixed(2) : '--';
        };

        stockInfoDiv.innerHTML = `
                <p><strong>当前价格:</strong> <span>¥${formatNumber(currentPrice)}</span></p>
                <p><strong>涨跌幅:</strong> <span class="${changeClass}">${changeIcon} ${formatNumber(changeRate)}%</span></p>
                <p><strong>分析周期:</strong> ${data.historyData ? data.historyData.length : 0} 个交易日</p>
                <p><strong>最新数据:</strong> ${data.historyData && data.historyData[0] ? data.historyData[0].date : '--'}</p>
                <p><strong>分析时间:</strong> ${new Date().toLocaleString()}</p>
            `;
    }

    // 显示K线图
    function displayKLineChart(historyData) {
        if (!historyData || historyData.length === 0) {
            document.getElementById('klineChart').innerHTML = '<p class="text-muted text-center">暂无历史数据</p>';
            return;
        }

        // 准备K线图数据
        const dates = [];
        const values = [];

        // 反转数据，让最早的数据在前
        const reversedData = [...historyData].reverse();

        reversedData.forEach(item => {
            dates.push(item.date);
            values.push([
                item.open || 0,
                item.close || 0,
                item.low || 0,
                item.high || 0,
                item.volume || 0
            ]);
        });

        const option = {
            animation: false,
            legend: {
                bottom: 10,
                left: 'center',
                data: ['K线', 'MA5', 'MA10', 'MA20']
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                },
                borderWidth: 1,
                borderColor: '#ccc',
                padding: 10,
                textStyle: {
                    color: '#000'
                },
                formatter: function (params) {
                    params = params[0];
                    const date = params.name;
                    const value = params.value;
                    return `
                            <div>日期: ${date}</div>
                            <div>开盘: ${value[1]}</div>
                            <div>收盘: ${value[2]}</div>
                            <div>最低: ${value[3]}</div>
                            <div>最高: ${value[4]}</div>
                            <div>成交量: ${(value[5] / 10000).toFixed(2)}万手</div>
                        `;
                }
            },
            xAxis: {
                type: 'category',
                data: dates,
                scale: true,
                boundaryGap: false,
                axisLine: { onZero: false },
                splitLine: { show: false },
                splitNumber: 20
            },
            yAxis: {
                scale: true,
                splitArea: { show: true }
            },
            dataZoom: [
                {
                    type: 'inside',
                    start: 50,
                    end: 100
                }
            ],
            series: [
                {
                    name: 'K线',
                    type: 'candlestick',
                    data: values,
                    itemStyle: {
                        color: '#ef232a',
                        color0: '#14b143',
                        borderColor: '#ef232a',
                        borderColor0: '#14b143'
                    }
                }
            ]
        };

        klineChart.setOption(option);
    }

    // 显示交易建议
    function displayTradingAdvice(advice) {
        const adviceCard = document.getElementById('adviceCard');
        const adviceContent = document.getElementById('adviceContent');

        if (!advice) {
            adviceContent.innerHTML = '<div class="alert alert-warning">暂无交易建议数据</div>';
            return;
        }

        // 设置卡片样式
        adviceCard.className = `card advice-${(advice.adviceType || 'HOLD').toLowerCase()}`;

        // 安全地格式化数字
        const formatNumber = (num) => {
            if (num === null || num === undefined) return '--';
            return typeof num === 'number' ? num.toFixed(2) : '--';
        };

        // 安全地处理置信度
        const confidence = advice.confidence || 0;

        adviceContent.innerHTML = `
                <div class="text-center mb-3">
                    <h4 class="text-${getAdviceColor(advice.adviceType)}">
                        ${advice.adviceDesc || '持有'}
                    </h4>
                    <div class="progress mb-2">
                        <div class="progress-bar bg-${getAdviceColor(advice.adviceType)}"
                             style="width: ${confidence * 100}%">
                            ${(confidence * 100).toFixed(1)}%
                        </div>
                    </div>
                    <small class="text-muted">置信度</small>
                </div>
                <p><strong>分析理由:</strong> ${advice.reasoning || '暂无详细分析理由'}</p>
                <div class="row">
                    <div class="col-6">
                        <strong>目标价格:</strong><br>
                        <span class="h5 text-success">¥${formatNumber(advice.targetPrice)}</span>
                    </div>
                    <div class="col-6">
                        <strong>止损价格:</strong><br>
                        <span class="h5 text-danger">¥${formatNumber(advice.stopLoss)}</span>
                    </div>
                </div>
                ${confidence === 0 ? '<div class="alert alert-warning mt-2"><small><i class="fas fa-exclamation-triangle"></i> 注：此建议基于本地技术分析生成</small></div>' : ''}
            `;
    }

    function getAdviceColor(adviceType) {
        switch (adviceType) {
            case 'BUY': return 'success';
            case 'SELL': return 'warning';
            case 'EXIT': return 'danger';
            default: return 'secondary';
        }
    }

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        // initChart();

        // 绑定回车键
        document.getElementById('stockCodeInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                analyzeStock();
            }
        });

        // 添加页面卸载时的清理
        window.addEventListener('beforeunload', function() {
            if (analysisTimeout) {
                clearTimeout(analysisTimeout);
            }
            if (progressInterval) {
                clearInterval(progressInterval);
            }
        });
    });
</script>
</body>
</html>